package com.cql.framework.web.exception;


import com.cql.common.constant.HttpStatus;
import com.cql.common.core.base.AjaxResult;
import com.cql.common.exception.BaseException;
import com.cql.common.exception.auth.AuthException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author cql
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("{},参数校验异常：{}", e.getMessage(), message);
        return AjaxResult.error(message);
    }


    /**
     * 其他系统异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        log.error("handleException {},{}", e.getMessage(), e);
        return AjaxResult.error(HttpStatus.InnerError.getMessage());
    }

    /**
     * 业务异常：比如验证码过期，验证码失效等
     */

    /**
     * 探店找不到异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public AjaxResult handleMomentNotExistException(BaseException e) {
        log.error("handleMomentNotExistException {},{}", e.getMessage(), e);
        return AjaxResult.error(HttpStatus.NotFound.getCode(), e.getMessage());
    }


    /**
     * 自定义无数据权限异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AuthException.class)
    public AjaxResult handleAuthException(AuthException e) {
        log.error("handleAuthException {},{}", e.getMessage(), e);
        return AjaxResult.error(HttpStatus.UNAUTHORITY.getCode(), e.getMessage());
    }

    /**
     * 无权限异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult handleAccessDeniedException(AccessDeniedException e) {
        log.error("handleAuthorizationException {} ", e.getMessage());
        return AjaxResult.error(HttpStatus.UNAUTHORITY.getCode(), HttpStatus.UNAUTHORITY.getMessage());
    }


}
